package javango.contrib.hibernate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javango.db.Managers;
import javango.forms.widgets.SelectMultipleWidget;
import javango.forms.widgets.WidgetFactory;

import com.google.inject.Inject;

public class ModelMultipleChoiceField<V> extends ModelChoiceField<V> {

	@Inject
	public ModelMultipleChoiceField(WidgetFactory widgetFactory, HibernateUtil hibernateUtil, Managers managers) {
		super(widgetFactory, hibernateUtil, managers);
		setWidget(SelectMultipleWidget.class);		
	}

	@Override
	public V[] clean(String values[], Map<String, String> errors) {
		if (values == null || values.length == 0) {
			if (isRequired()) { 
				errors.put(getName(), REQUIRED_ERROR);
			} else if (isAllowNull()) {
				return null;
			}
			return (V[])new Object[0]; // humm  wonder what this should be
		} else {
			V[] clean = (V[])new Object[values.length];
			int i=0;
			for(String val : values) {
				Object cleanValue = clean(val, errors);
				if (cleanValue != null) {
					clean[i++] = (V)cleanValue;
				}
			}
			return clean;
		}
	}

        // take an initial list of object or object primary keys and return a list of primary keys as that is what the widget will render
        @Override
        public Object cleanInitialValue(Object value) {
                List<Object> keys = new ArrayList<Object>();
                if (value instanceof Iterable) {
                        for(V o : (Iterable<V>)value) {
                                keys.add(super.cleanInitialValue(o));
                        }
                }

                return keys;
        }

}
